<template>
  <div class="dialog">
    <el-dialog :title="'批次' + titleText" :visible.sync="showDialog" width="60%" top="0" :close-on-click-modal="false"
      @close="cancel">
      <el-form ref="ruleForm" label-position="left" :model="formData" :rules="rules" class="el-form">
        <el-row :gutter="15">
          <el-form-item label="选择批次:" prop="batchId" class="w100p">
            <el-select filterable clearable v-model="formData.batchId" placeholder="请选择">
              <el-option v-for="item in batchList" :key="item.productionBatchId"
                :label="`${item.mnecode}_${item.varietyName}`" :value="item.productionBatchId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row :gutter="15">
          <el-form-item label="可见范围:" prop="rangeList">
            <el-checkbox-group v-model="formData.rangeList" @change="handleCheckedCitiesChange">
              <el-checkbox v-for="city in checkInfoList" :label="city.value" :key="city.value">{{ city.label
              }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-row>
        <el-row :gutter="15">
          <el-form-item label="基础内容:" class="w100p">
            <template v-for="element in draggableList">
              <div class="basics-item" v-if="showItem.indexOf(element.value) !== -1" :key="element.value">{{
                element.label }}</div>
            </template>
          </el-form-item>
        </el-row>
        <el-row :gutter="15">
          <el-form-item label="阶段内容排序:" class="w100p">
            <draggable class="w100p" v-model="draggableList" animation="1000" @start="onStart" @end="onEnd">
              <transition-group class="transition-group">
                <template v-for="element in draggableList">
                  <div class="transition-group-item" v-if="showItem.indexOf(element.value) == -1" :key="element.value">{{
                    element.label }}</div>
                </template>
              </transition-group>
            </draggable>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
        <el-button type="primary" class="savebtn" @click="save('ruleForm')">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import QRCodeMsgApi from "@/api/traceability/basicsInfo/QRCodeMsg";
import draggable from 'vuedraggable'

export default {
  name: '',
  components: {},
  props: {
    // 弹框名称
    titleText: {
      type: String,
      default: ""
    },
    nowChanceStau: {
      type: String,
      default: ""
    },
    show: {
      type: Boolean,
      default: false
    },
    batchList: {
      type: Array,
      default: false
    },
    checkInfoList: {
      type: Array,
      default: false
    },
    editObject: {
      type: [Object],
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      showItem: ['1', '2', '3', '4'],
      drag: false,
      rules: {
        batchId: [
          { required: true, message: "请选择批次", trigger: ["change", "blur"] }
        ],
        rangeList: [
          { required: true, message: "请选择范围", trigger: ["change", "blur"] }
        ],
      },
      formData: {},
      showDialog: this.show,
      draggableList: []
    };
  },
  components: {
    draggable,
  },
  watch: {
    show(v) {
      this.showDialog = v;
      if (!v) {
        this.varietyName = null
        console.log('重置表单验证')
      }
      this.$refs['ruleForm'] && this.$refs['ruleForm'].resetFields();
    },
    nowChanceStau(v) {
      console.log(v, 'fasdsfas')
      if (v === 'add') {
        this.formData = {
          rangeList: []
        }
      }
      if (v === 'edit') {
        if (this.editObject.range) {
          this.formData['rangeList'] = this.editObject.range.split(",")
        } else {
          this.formData['rangeList'] = []
        }
        this.handleCheckedCitiesChange(this.formData['rangeList'])
        console.log(this.editObject, this.formData)
        this.formData = { ...this.formData, ...this.editObject }
      }
    }
  },
  created() {
  },
  mounted() {
  },
  methods: {
    onStart() {
      this.drag = true;
    },
    //拖拽结束事件
    onEnd(e) {
      console.log(e)
      this.drag = false;
      let rangeList = [];
      this.draggableList.forEach(item => {
        rangeList.push(item.value)
      });
      this.formData.range = rangeList.join(',');
    },
    isJSON(str) {
      if (typeof str == 'string') {
        try {
          var obj = JSON.parse(str);
          // 等于这个条件说明就是JSON字符串 会返回true
          if (typeof obj == 'object' && obj) {
            return true;
          } else {
            //不是就返回false
            return false;
          }
        } catch (e) {
          return false;
        }
      }
      return false;
    },
    // 多选
    handleCheckedCitiesChange(value) {
      let rangeList = [];
      this.draggableList = this.checkInfoList.filter(item => {
        if (value.indexOf(item.value) !== -1) {
          rangeList.push(item.value)
        };
        return value.indexOf(item.value) !== -1;
      });
    },
    //保存
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          let rangeList = [];
          this.draggableList.forEach(item => {
            rangeList.push(item.value)
          });
          this.formData.range = rangeList.join(',');
          if (this.nowChanceStau === "edit") {
            QRCodeMsgApi.edit(this.formData).then(res => {
              if (res.success === true) {
                this.$message.success("修改成功！");
                this.close()
              } else {
                this.$message.error(res.message);
              }
            });
          } else if (this.nowChanceStau === "add") {
            QRCodeMsgApi.add(this.formData).then(res => {
              if (res.success === true) {
                this.$message.success("添加成功！");
                this.close()
              } else {
                this.$message.error(res.message);
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    close() {
      this.useableRate = undefined
      this.$emit("closeDialog");
    },
    cancel() {
      this.$emit("cancelDialog");
    }
  }
};
</script>

<style lang="scss" scoped>
.transition-group {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
}

.basics-item {
  margin: 4px 10px;
  padding: 0 15px;
  border: 1px solid #0c5ca7;
  background: #d1e3ff;
  border-radius: 4px;
  color: #4e86c7;
  cursor: pointer;
}

.transition-group-item {
  margin: 4px 10px;
  padding: 0 15px;
  border: 1px solid #4eafc7;
  background: #d8f7ff;
  border-radius: 4px;
  color: #4eafc7;
  cursor: pointer;

  &:hover {
    background: #90d3e4;
    color: #ffffff;
  }
}
</style>
